package com.roncoo.education.course.service.api.biz;

import java.util.HashMap;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.roncoo.education.common.core.base.Result;
import com.roncoo.education.common.core.enums.StatusIdEnum;
import com.roncoo.education.common.core.tools.BeanUtil;
import com.roncoo.education.common.service.BaseBiz;
import com.roncoo.education.course.dao.CourseChapterPeriodDao;
import com.roncoo.education.course.dao.impl.mapper.entity.CourseChapterPeriod;
import com.roncoo.education.course.service.api.resp.ApiCourseChapterPeriodResp;

import lombok.RequiredArgsConstructor;

/**
 * API-课时信息
 *
 * @author wujing
 */
@Component
@RequiredArgsConstructor
public class ApiCourseChapterPeriodBiz extends BaseBiz {

    @NotNull
    private final CourseChapterPeriodDao dao;

    /**
     * 课程附件分组预览接口
     *
     * @return
     */
    public Result<ApiCourseChapterPeriodResp> view(Long periodId) {
    	CourseChapterPeriod period = dao.getById(periodId);
        if (period == null) {
            return Result.error("找不到课时信息");
        }
        if (!period.getStatusId().equals(StatusIdEnum.YES.getCode())) {
            return Result.error("该课时已被禁用");
        }
        
        if (StringUtils.isBlank(period.getAttachments())) {
        	return Result.error("该课时没有可预览的附件");        	
        }
        
        Map<String, String> attachmentContentTypes = new HashMap<String, String>();
        JSONArray array = JSONArray.parseArray(period.getAttachments());
    	for (Object item : array) {
			System.out.println(array);
			Map map = (Map) item;
			String fileName = MapUtils.getString(map, "fileName");
			String contentType = MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
			attachmentContentTypes.put(fileName, contentType);
		}
    	
        ApiCourseChapterPeriodResp periodResp = BeanUtil.copyProperties(period, ApiCourseChapterPeriodResp.class);
        periodResp.setAttachmentContentTypes(attachmentContentTypes);        
        return Result.success(periodResp);
    }
}
